package com.boot.security.server.controller;

import java.util.List;

import com.boot.security.server.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.dao.SysAreaDao;
import com.boot.security.server.model.SysArea;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/sysAreas")
public class SysAreaController {

    @Autowired
    private SysAreaDao sysAreaDao;

    @PreAuthorize("hasAuthority('area:add')")
    @PostMapping
    @ApiOperation(value = "保存")
    public SysArea save(@RequestBody SysArea sysArea) {
        sysArea.setId(UUIDUtils.getID());
        sysAreaDao.save(sysArea);
        return sysArea;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取")
    public SysArea get(@PathVariable String id) {
        return sysAreaDao.getById(id);
    }

    @PreAuthorize("hasAuthority('area:add')")
    @PutMapping
    @ApiOperation(value = "修改")
    public SysArea update(@RequestBody SysArea sysArea) {
        sysAreaDao.update(sysArea);
        return sysArea;
    }

    @PreAuthorize("hasAuthority('area:query')")
    @GetMapping
    @ApiOperation(value = "列表")
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return sysAreaDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<SysArea> list(PageTableRequest request) {
                List<SysArea> lists = sysAreaDao.list(request.getParams(), request.getOffset(), request.getLimit());
                return lists;
            }
        }).handle(request);
    }

    @PreAuthorize("hasAuthority('area:del')")
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public void delete(@PathVariable String id) {
        sysAreaDao.delete(id);
    }
}
